﻿using System;
using kad2SimSoft.Classes;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Windows.Controls.Primitives;
using System.Collections.ObjectModel;
using kad2SimSoft.Resources.Lokalisierung;

namespace kad2SimSoft
{
    /// <summary>
    /// Interaktionslogik für ProductionOrderControl.xaml
    /// </summary>
    public partial class ProductionOrderControl : UserControl
    {
        private List<Order> _orders = new List<Order>();
        private List<Endproduct> _enproducts;
        private List<OrdersInWork> _ordersInWork;
        private List<Workplace> _workplaces;
        private List<ManufacturedPart> _manufacturedParts;
        private ObservableCollection<DisplayObjectOrder> _modifiedDataGridOrders = null;
        private ObservableCollection<DisplayObjectOrder> _defaultDataGridOrders = null;
        private DisplayObjectOrder selectedOrder = null;
        private MainWindow _mainWindow;

        public ProductionOrderControl(List<Endproduct> enproducts, List<ManufacturedPart> manufacturedParts, List<OrdersInWork> ordersInWork, List<Workplace> workplaces, MainWindow main)
        {
            InitializeComponent();
            _enproducts = enproducts;
            _manufacturedParts = manufacturedParts;
            _ordersInWork = ordersInWork;
            _workplaces = workplaces;
            _orders = main.ProducionPlanningView.CreateListOforders();
            _mainWindow = main;
            initProductionOrderList();
        }

        private void initProductionOrderList()
        {
            _modifiedDataGridOrders = new ObservableCollection<DisplayObjectOrder>();
            foreach (Order order in _orders)
            {
                if (order.Amount > 0)
                {
                    DisplayObjectOrder displayOrder = new DisplayObjectOrder();
                    displayOrder.ProductId = order.Product.Type + order.Product.Id;
                    displayOrder.ProductDescription = order.Product.Description;
                    displayOrder.ProductionAmount = order.Amount;
                    foreach (OrdersInWork orderInWork in _ordersInWork)
                    {
                        if (orderInWork.Item.Equals(order.Product.Id))
                        {
                            displayOrder.OrdersInWorkAmount += orderInWork.Amount;
                        }
                    }
                    foreach (Workplace workplace in _workplaces)
                    {
                        foreach (WaitinglistWorkplace waitinglist in workplace.WaitingList)
                        {
                            if (waitinglist.Item.Equals(order.Product.Id))
                            {
                                displayOrder.WaitinglistAmount += waitinglist.Amount;
                            }
                        }
                    }
                    displayOrder.SummarizedAmount = displayOrder.OrdersInWorkAmount + displayOrder.WaitinglistAmount;
                    _modifiedDataGridOrders.Add(displayOrder);
                }
            }

            foreach (DisplayObjectOrder displayedOrder in _modifiedDataGridOrders)
            {
                bool found = false;
                foreach (Endproduct product in _enproducts)
                {
                    if ((product.Type + product.Id).Equals(displayedOrder.ProductId))
                    {
                        displayedOrder.CurrentStockAmount = product.Amount;
                        displayedOrder.SummarizedAmount += product.Amount;
                        found = true;
                        continue;
                    }
                }

                if (!found)
                {
                    foreach (ManufacturedPart product in _manufacturedParts)
                    {
                        if ((product.Type + product.Id).Equals(displayedOrder.ProductId))
                        {
                            displayedOrder.CurrentStockAmount = product.Amount;
                            displayedOrder.SummarizedAmount += product.Amount;
                            continue;
                        }
                    }
                }
            }
            _defaultDataGridOrders = new ObservableCollection<DisplayObjectOrder>(_modifiedDataGridOrders.OrderBy(order => order));
            _modifiedDataGridOrders = new ObservableCollection<DisplayObjectOrder>(_modifiedDataGridOrders.OrderBy(order => order));
            dataGrid.ItemsSource = _modifiedDataGridOrders;
            //_modifiedDataGridOrders = (ObservableCollection<DisplayObjectOrder>)_modifiedDataGridOrders.OrderByDescending(a => a.CurrentStockAmount);
            MySource = CollectionViewSource.GetDefaultView(_modifiedDataGridOrders);
        }

        public ICollectionView MySource { get; set; }

        private class DisplayObjectOrder : IComparable
        {
            public string ProductId { get; set; }
            public string ProductDescription { get; set; }
            public int ProductionAmount { get; set; }
            public int CurrentStockAmount { get; set; }
            public int OrdersInWorkAmount { get; set; }
            public int WaitinglistAmount { get; set; }
            public int SummarizedAmount { get; set; }
            public int CompareTo(object obj)
            {
                DisplayObjectOrder order = obj as DisplayObjectOrder;
                if (order == null)
                {
                    throw new ArgumentException("Object is not an order");
                }
                return this.SummarizedAmount.CompareTo(order.SummarizedAmount);
            }
        }

        private void Button_SplitOrder_Click(object sender, RoutedEventArgs e)
        {
            selectedOrder = (DisplayObjectOrder)dataGrid.SelectedItem;
            ProductionOrderSplitPopup popUp = new ProductionOrderSplitPopup(selectedOrder.ProductionAmount);
            popUp.ShowDialog();
            if (!popUp.Canceled)
            {
                selectedOrder.ProductionAmount = popUp.Order1_amount;
                _modifiedDataGridOrders.Add(new DisplayObjectOrder
                {
                    ProductId = selectedOrder.ProductId,
                    ProductDescription = selectedOrder.ProductDescription,
                    CurrentStockAmount = selectedOrder.CurrentStockAmount,
                    OrdersInWorkAmount = selectedOrder.OrdersInWorkAmount,
                    WaitinglistAmount = selectedOrder.WaitinglistAmount,
                    SummarizedAmount = selectedOrder.SummarizedAmount,
                    ProductionAmount = popUp.Order2_amount
                }
);
                dataGrid.Items.Refresh();
            }
        }

        private void Button_DeleteOrder_Click(object sender, RoutedEventArgs e)
        {
            selectedOrder = (DisplayObjectOrder)dataGrid.SelectedItem;
            if (MessageBox.Show(kad2SimSoft.Properties.Resources.msgDeleteOrder + "\n" + selectedOrder.ProductId, "" , MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {

                foreach (DisplayObjectOrder order in _modifiedDataGridOrders)
                {
                    if (order.ProductId.Equals(selectedOrder.ProductId) && order != selectedOrder)
                    {
                        order.ProductionAmount += selectedOrder.ProductionAmount;
                        break;
                    }
                }
                _modifiedDataGridOrders.Remove(selectedOrder);
                dataGrid.Items.Refresh();
            }
            _mainWindow.CapacityPlanView = null;
            _mainWindow.PurchasingView = null;
            _mainWindow.setButtonsDisabledAfterOrderPlanning();
        }

        private void Button_OrderUp_Click(object sender, RoutedEventArgs e)
        {
            DisplayObjectOrder helpOrder = new DisplayObjectOrder();
            if (dataGrid.SelectedIndex != 0)
            {
                helpOrder = (DisplayObjectOrder)dataGrid.Items[dataGrid.SelectedIndex - 1];
                _modifiedDataGridOrders[dataGrid.SelectedIndex - 1] = _modifiedDataGridOrders[dataGrid.SelectedIndex];
                _modifiedDataGridOrders[dataGrid.SelectedIndex] = helpOrder;
            }
            dataGrid.Items.Refresh();
        }

        private void Button_OrderDown_Click(object sender, RoutedEventArgs e)
        {
            DisplayObjectOrder helpOrder = new DisplayObjectOrder();
            if (dataGrid.SelectedIndex != dataGrid.Items.Count - 1)
            {
                helpOrder = (DisplayObjectOrder)dataGrid.Items[dataGrid.SelectedIndex + 1];
                _modifiedDataGridOrders[dataGrid.SelectedIndex + 1] = _modifiedDataGridOrders[dataGrid.SelectedIndex];
                _modifiedDataGridOrders[dataGrid.SelectedIndex] = helpOrder;
            }
            dataGrid.Items.Refresh();
        }

        private void Button_Reload_Click(object sender, RoutedEventArgs e)
        {
            dataGrid.ItemsSource = null;
            _modifiedDataGridOrders = new ObservableCollection<DisplayObjectOrder>(_defaultDataGridOrders);
            dataGrid.ItemsSource = _modifiedDataGridOrders;
            MySource = CollectionViewSource.GetDefaultView(_modifiedDataGridOrders);
            dataGrid.Items.Refresh();
        }

        public List<Order> getSortedOrderList()
        {
            List<Order> sortedOrderList = new List<Order>();
            int index = 0;
            foreach (var item in MySource.OfType<DisplayObjectOrder>())
            {
                Order order = new Order();
                Product product = null;
                if (item.ProductId.ElementAt(0).Equals("P"))
                {
                    product = new Endproduct();
                    product.Type = "P";
                    product.Amount = item.CurrentStockAmount;
                    product.Description = item.ProductDescription;
                    product.Id = Convert.ToInt32(item.ProductId.Substring(1, item.ProductId.Length - 1));
                }
                else
                {
                    product = new ManufacturedPart();
                    product.Type = "M";
                    product.Amount = item.CurrentStockAmount;
                    product.Description = item.ProductDescription;
                    product.Id = Convert.ToInt32(item.ProductId.Substring(1, item.ProductId.Length - 1));
                }
                order.Product = product;
                order.Id = index;
                order.Amount = item.ProductionAmount;
                index++;
                sortedOrderList.Add(order);
            }
            return sortedOrderList;
        }

        public static MainWindow FindPageControl(DependencyObject child)
        {
            DependencyObject parent = VisualTreeHelper.GetParent(child);

            if (parent == null) return null;

            MainWindow page = parent as MainWindow;
            if (page != null)
            {
                return page;
            }
            else
            {
                return FindPageControl(parent);
            }
        }

        private void Button_BackToProdPlanning_Click(object sender, RoutedEventArgs e)
        {
            FindPageControl(this).btOrderPlanning.IsChecked = false;
            _mainWindow.ChangeViewTo(MainWindow.VIEWTYPE.PRODUCTIONPLANNING);
        }

        private void Button_NextToCapacityPlanning_Click(object sender, RoutedEventArgs e)
        {

            FindPageControl(this).btOrderPlanning.IsChecked = false;
            FindPageControl(this).btCapacityPlanning.IsChecked = true;
            FindPageControl(this).setButtonsEnabledAfterOrderPlanning();
            _mainWindow.ChangeViewTo(MainWindow.VIEWTYPE.CAPACITY);
        }
    }
}
